package application;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import kernel.Disk;
import kernel.FileManage;
import kernel.FileMsg;
import uiTip.UiTip;

public class Build implements Initializable
{

	@FXML
	private TextField textName;

	@FXML
	private TextField textTypeName;

	@FXML
	private RadioButton dir;

	@FXML
	private RadioButton file;

	@FXML
	private RadioButton onlyReadFile;

	@FXML
	private Button btnSubmit;
	public Button btn;
	public Stage readStage;
	public Stage writeStage;
	public FileMsg msg;
	public ArrayList<FileMsg> filePath;// 指向文件的路径

	@Override
	public void initialize(URL location, ResourceBundle resources)
	{
		/*
		 * 这两个设置不能输入超过要求的字母数，但无法限制汉字、“$”、“.”、“/”字符。
		 */
		textName.setOnKeyTyped(new EventHandler<KeyEvent>()
		{
			@Override
			public void handle(KeyEvent e)
			{
				String s = textName.getText();
				if (s.length() >= 3)
					e.consume();
			}
		});
		textTypeName.setOnKeyTyped(new EventHandler<KeyEvent>()
		{
			@Override
			public void handle(KeyEvent e)
			{
				String s = textTypeName.getText();
				if (s.length() >= 2)
					e.consume();
			}
		});

		/*
		 * 这个设置点击提交按钮
		 */
		btnSubmit.setOnAction(e -> {
			String textNameStr = textName.getText().trim();
			String textTypeNameStr = textTypeName.getText().trim();
			if(textNameStr.contains("$")||textNameStr.contains(".")||textNameStr.contains("/")) {
				UiTip.tip("文件名不能包含“$”、“.”、“/”字符。");
				return;
			}
			int attribute = 0;
			if (dir.isSelected())
			{
				attribute = 8;
			} else if (file.isSelected())
			{
				attribute = 4;
			} else if (onlyReadFile.isSelected())
			{
				attribute = 3;
			}
			// System.out.println(textNameStr + "." + textTypeNameStr + " " + attribute);
			SamplePane.stage.close();

			newFileAndFolder(textNameStr, textTypeNameStr, attribute);

		});
	}

	public void newFileAndFolder(String textNameStr, String textTypeNameStr, int attribute)
	{
		if (textNameStr.length() == 0)
		{
			textNameStr = "aut";// 代表自动生成的
		}
		if (textTypeNameStr.length() == 0)
		{
			textTypeNameStr = "au";
		}
		/* FileMsg msg; */
		if (attribute == 8)
		{
			if ((msg = FileManage.md(textNameStr, Contain.path)) != null)
			{
				try
				{
					filePath = FileManage.clonePath(Contain.path);
				} catch (CloneNotSupportedException e)
				{
					e.printStackTrace();
				}
				filePath.add(msg);

				// 视图
				Label theItem = new Label(msg.getAllName(), new ImageView(new Image("/image/catalogue.png")));
				theItem.setContentDisplay(ContentDisplay.TOP);
				btn = new Button();
				btn.setGraphic(theItem);
				setRightMenuFolder(/* btn */);
				Contain.rootPane.getChildren().add(btn);

				// 把当前的FileMsg和Button加入到map里
				Contain.map.put(msg, btn);
			}

		} else
		{
			if ((msg = FileManage.create_file(textNameStr, textTypeNameStr, (byte) attribute, Contain.path)) != null)
			{
				// 得到指向当前文件的路径
				try
				{
					filePath = FileManage.clonePath(Contain.path);
				} catch (CloneNotSupportedException e)
				{
					e.printStackTrace();
				}
				filePath.add(msg);// filePath是个指向当前文件的路径
				// 视图
				Label theItem = new Label(msg.getAllName(), new ImageView(new Image("/image/file.png")));
				theItem.setContentDisplay(ContentDisplay.TOP);
				btn = new Button();
				btn.setGraphic(theItem);
				setRightMenuFile(btn);
				Contain.rootPane.getChildren().add(btn);

				// 把当前的FileMsg和Button加入到map里
				Contain.map.put(msg, btn);
			}
		}
	}

	private void setRightMenuFolder(/* Button btn */)
	{
		ContextMenu rightMenu = new ContextMenu();

		MenuItem displayFolderItem = new MenuItem("显示目录内容");
		displayFolderItem.setOnAction((a) -> {
			Contain.path.add(msg);

			HashMap<FileMsg, Button> map = FileManage.dir(Contain.path, Contain.map);
			Set<Map.Entry<FileMsg, Button>> entryAll = Contain.map.entrySet();
			for (Map.Entry<FileMsg, Button> ent : entryAll)
			{
				ent.getValue().setVisible(false);
				ent.getValue().setManaged(false);
			}

			Set<Map.Entry<FileMsg, Button>> entry = map.entrySet();
			for (Map.Entry<FileMsg, Button> ent : entry)
			{
				ent.getValue().setVisible(true);
				ent.getValue().setManaged(true);
			}
		});
		MenuItem removeFolderItem = new MenuItem("删除空目录");
		removeFolderItem.setOnAction((a) -> {
			try
			{
				if (FileManage.rd(filePath) != -1)
				{
					Contain.rootPane.getChildren().remove(this.btn);
					Contain.map.remove(msg);
				}
			} catch (CloneNotSupportedException e)
			{
				e.printStackTrace();
			}
		});
		rightMenu.getItems().addAll(displayFolderItem, removeFolderItem);
		btn.setContextMenu(rightMenu);
	}

	private void setRightMenuFile(Button btn)
	{
		ContextMenu rightMenu = new ContextMenu();

		MenuItem readFileItem = new MenuItem("读文件");
		readFileItem.setOnAction((a) -> {

			String text = null;
			try
			{
				int listNum = FileManage.getListNum(filePath.get(filePath.size()-1).getStartBlock(),
						Disk.readBlock(filePath.get(filePath.size()-2).getStartBlock()));
				//下面文件所占的磁盘块数这里得从磁盘读，因为对象里的内容没有改。
				text = FileManage.read_file(filePath, Disk.readOnlyByte(filePath.get(filePath.size()-2).getStartBlock(), listNum, 7)/*msg.getLength()*/ * 64);
			} catch (UnsupportedEncodingException e)
			{
				e.printStackTrace();
			} catch (CloneNotSupportedException e)
			{
				e.printStackTrace();
			}
			if (text != null)
			{
				readStage = new Stage();
				Label lable = new Label(text);
				Scene s = new Scene(lable, 800, 700);
				readStage.setScene(s);
				readStage.show();
			}
		});

		MenuItem writeFileItem = new MenuItem("写文件");
		writeFileItem.setOnAction((a) -> {
			TextArea textArea = new TextArea();
			textArea.setWrapText(true);
			Button writeBtn = new Button("写入");
			writeBtn.setOnAction(e -> {
				String text = textArea.getText();
				try
				{
					FileManage.write_file(filePath, text.getBytes("utf8"), text.getBytes().length);
				} catch (CloneNotSupportedException e1)
				{
					e1.printStackTrace();
				} catch (UnsupportedEncodingException e1)
				{
					e1.printStackTrace();
				}
			});
			VBox vBox = new VBox();
			vBox.getChildren().addAll(textArea, writeBtn);
			writeStage = new Stage();
			Scene s = new Scene(vBox/* ,200,100 */);
			writeStage.setScene(s);
			writeStage.show();
		});

		MenuItem closeFileItem = new MenuItem("关闭文件");
		closeFileItem.setOnAction((a) -> {
			FileManage.close_file(filePath);
			if (readStage != null)
			{
				readStage.close();
			}
			if (writeStage != null)
			{
				writeStage.close();
			}
		});

		MenuItem deleteFileItem = new MenuItem("删除文件");
		deleteFileItem.setOnAction((a) -> {
			try
			{
				if ((FileManage.delete_file(filePath)) != -1)
				{
					Contain.rootPane.getChildren().remove(this.btn);
					Contain.map.remove(msg);//用输出返回值是不是null来测试是否删除
				}
			} catch (CloneNotSupportedException e)
			{
				e.printStackTrace();
			}
		});

		MenuItem typeFileItem = new MenuItem("显示文件内容");
		typeFileItem.setOnAction((a) -> {
			String text = null;
			try
			{
				text = FileManage.typeFile(filePath);
			} catch (CloneNotSupportedException e)
			{
				e.printStackTrace();
			}
			if (text != null)
			{
				readStage = new Stage();
				Label lable = new Label(text);
				Scene s = new Scene(lable, 800, 700);
				readStage.setScene(s);
				readStage.show();
			}
		});

		MenuItem changeFileItem = new MenuItem("改变文件属性");
		changeFileItem.setOnAction((a) -> {
			byte attribute = msg.getAttribute();
			if (attribute == 4)
			{
				attribute = 3;
			} else if (attribute == 3)
			{
				attribute = 4;
			}
			try
			{
				if (FileManage.change(filePath, attribute) != -1)
				{
					UiTip.tip("已改变文件属性为：" + ((attribute == 4) ? "普通文件" : "系统只读文件"));
				}
			} catch (CloneNotSupportedException e)
			{
				e.printStackTrace();
			}

		});

		rightMenu.getItems().addAll(readFileItem, writeFileItem, closeFileItem, deleteFileItem, typeFileItem,
				changeFileItem);
		btn.setContextMenu(rightMenu);
	}
}
